/**
 * cs340 Fatboy Mafia Team 
 */
package fatboy.communication;

import java.io.IOException;
import java.net.ServerSocket;


/**
 * 
 * This is a multi-threaded version of the communication server for the hyper web.  
 *	Server is a thread itself that listens on a particular port of the application.
 *	For each incoming connection it creates a ServerThread thread to process the
 *	information send to it. (i.e. Whenever it establishes a connection, it delegates
 *	connection processing to a ServerThread instance.)
 *
 *	@domain an instance of the Server thread with the unique port number to this machine
 *  @author Ilya Vinogradov
 *	@date 23-Jan-10 11:17 PM
 */
public class Server extends Thread {

	/** Stores the socket object */
	ServerSocket serverSocket = null;
	
	/** Indicates whether to accept more connections or not */
	//boolean listening = true;

	public Server() {
		super("Server");
		
		// Creating listening socket
		boolean failing = true;
		while(failing){
			try {
				serverSocket = new ServerSocket(PortNumber.getRuntimePort().getPort());
				failing = false;
			} catch (IOException e) {
				int port = PortNumber.getRuntimePort().getPort();
				PortNumber.setRuntimePort(port+1);
			}
		}
	}

	/**
	 * Server thread body. Listens for a connection on a specific port. As soon as
	 * 	it receives the incoming connection, it creates a new ServerThread tread and
	 * 	delegates the handling of the connection to it. In the mean time it continues
	 * 	listening.
	 * 
	 * 	@pre An open port number should be provided.
	 * 	@post Listens on the port provided. If it receives the incoming connection, 
	 * 	ServerThread thread processes it, while this thread continues listening 
	 */
	public void run() {	
		System.out.println("\nServer: Listening for connections on port " 
				+ PortNumber.getRuntimePort().getPort());
		
		
		
		//run method should already run forever, uncomment the while loop if I'm wrong
		while (true) {
			try {
				sleep(0);
				new ServerThread(serverSocket.accept()).start();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			catch (InterruptedException e) {
	        //We've been interrupted: no more messages.
	        return;
			}
		}

		//Close the listener (for now this is never going to happened)
		/*try {
			serverSocket.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}*/

	}
		
}
